﻿var http = require("http");
var queryString = require('querystring');
var mysql = require('mysql');
var async = require('async');

createDataServer();

function createDataServer() {
    http.createServer(function(request, response) {
        // 定义了一个post变量，用于暂存请求体的信息
        var post = '';
        request.on('data', function(chunk) {
            post += chunk;
        });
        // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
        request.on('end', function() {
            post = queryString.parse(post);
            var result = 'aa';
            async.parallel([function(cb) {
                switch (post.type) {
                    case "insert":
                        console.log("latitude" + post.latitude);
                        console.log("longitude" + post.longitude);
                        insertPosition(post.latitude, post.longitude);
                        result = "上传位置成功"
                        response.writeHead(200, {
                            "Content-Type": "text/plain;charset=utf8"
                        });
                        response.write(result);
                        response.end();
                        break;
                    case "getDistribute":
                        async.parallel([function(cb) {
                            getPosition(cb);
                        }], function(err, tx) {
                            response.writeHead(200, {
                                "Content-Type": "application/json;charset=utf8"
                            });
                            response.end(tx[0]);
                            console.log(tx[0]);
                        });
                        break;
                    default:
                        break;
                }
            }], function(err, tx) {
                console.log("请求结束");
            });
        });

    }).listen(8888);
    console.log("服务器启动在端口8888");
}


/**
 * [插入位置数据]
 * @param  {[Number]} X [纬度]
 * @param  {[Number]} Y [经度]
 * @return {[Number]}   [description]
 */
function insertPosition(X, Y) {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        database: 'test'
    });


    connection.connect();

    var sql = 'INSERT INTO position set ?';
    var usr = {
        X: X,
        Y: Y
    };

    connection.query(sql, usr, function(err, result) {
        if (err) {
            console.log('[INSERT ERROR] - ', err.message);
            return;
        }

        console.log('--------------------------INSERT----------------------------');
        console.log(result);
        console.log('------------------------------------------------------------\n\n');
    });

    connection.end();
}

function getPosition(cb) {

    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        database: 'test'
    });

    var sql = 'SELECT * FROM position';
    var json;
    connection.connect();

    async.parallel([function(cd) {
        connection.query(sql, function(err, result) {
            if (err) {
                console.log('[SELECT ERROR] - ', err.message);
                return;
            }
            json = JSON.stringify(result);
            console.log('--------------------------SELECT----------------------------');
            console.log(typeof(result));
            console.log(result);
            console.log('------------------------------------------------------------\n\n');
        });

        return cd(null, json);
    }], function(err, tx) {
        connection.end();
        return cb(null, tx[0]);
    });
}